<template>
  <div class="createApplyForm">
    <group label-width="1rem" label-align="left" gutter="0">
      <!--<x-input title="工单编号" v-model="workOrderCode" :required="true">-->
      <!--<img slot="right-full-height" src="~assets/images2/icon_zuojian@2x.png">-->
      <!--</x-input>-->
      <selector :required="true" title="工单编号" v-model="workOrderCode" :options="workOrderList"></selector>
    </group>
    <tab style="margin-top: 10px" v-model="currentIndex">
      <tab-item v-for="(item, index) in contentList" :key="index" :selected="index===currentIndex">
        <span v-if="index===currentIndex&&contentList.length > 1">明细{{ (index+1) }} <span
          @click="removeTab(index)"> <icon type="cancel"></icon></span></span>
        <span v-else="index ===currentIndex">明细{{ (index+1)  }}</span>
      </tab-item>
    </tab>
    <swiper ref="swiper" :threshold="10000" :min-moving-distance="10000" v-model="currentIndex" :show-dots="false"
            @on-index-change="setHeight">
      <swiper-item v-for="(item, index) in contentList" :key="index">
        <CostApplyForm v-if="index==currentIndex" ref="swiper_item" v-on:heightChange='setHeight' :formdata="item"
                       :current="currentIndex" :contentList="contentList"></CostApplyForm>
      </swiper-item>
    </swiper>
    <div class="add-item blue" @click="addTab">
      添加费用
    </div>
    <div class="clearfix"></div>
    <group label-width="1rem" label-align="left">
      <cell title="合计">
        <span slot="after-title">{{allFillAmount}}</span>
      </cell>
    </group>
    <group class="addPerson" gutter="10px">
      <p>审核人</p>
      <span>
        提交人一次性选择好所有的相关初审人,系统将根据选择的初审人流转单据,初审人审批通过后由复核人最终审核
      </span>
      <ol>
        <li v-for="(item,index) in approvalList" v-if="item.checked">
          <div class="item_box">
            <i class="fa fa-minus-circle" @click="item.checked =false"></i>
            <img src="~assets/images3/user_defualt.jpg" alt="">
            <div>{{item.nickName}}</div>
          </div>
        </li>
        <li>
          <div class="item_box">
            <img src="~assets/images3/icon-ttianjia@3x.png" alt="" @click="addApproval(approvalList)">
          </div>
        </li>
      </ol>
    </group>
    <flexbox>
      <flexbox-item>
        <x-button type="warn" @click.native="cancelCommit">
          <icon type="cancel"></icon>
          取消
        </x-button>
      </flexbox-item>
      <flexbox-item style="margin-left: 0">
        <x-button type="primary" @click.native="submitExpense(1)">
          <icon type="success-circle"></icon>
          提交
        </x-button>
      </flexbox-item>
    </flexbox>
    <div v-transfer-dom>
      <popup v-model="sprPopup" height="90%">
        <popup-header
          left-text="取消"
          right-text="确认"
          title="选择审核人"
          :show-bottom-border="false"
          @on-click-left="addApprovalSure(approvalList)"
          @on-click-right="addApprovalSure"></popup-header>
        <ChoiceApprover v-on:addApproval="addApprovalSure" :list="approvalList"></ChoiceApprover>
      </popup>
    </div>
  </div>
</template>

<script>
  import {
    Group, XInput, XTextarea, Selector, Cell, FormPreview, Icon, XButton, Flexbox, FlexboxItem, Tab, TabItem, Swiper,
    SwiperItem, Popup, XSwitch, TransferDom, PopupHeader
  } from 'vux';
  import CostApplyForm from './costApplyForm.vue'
  import UploadImage from './uploadImage.vue'
  import ChoiceApprover from './choiceApprover.vue'

  export default {
    name: "createApplyForm",
    directives: {
      TransferDom
    },
    components: {
      Group, XInput, XTextarea, Selector, Cell, FormPreview, Icon,
      XButton, Flexbox, FlexboxItem, Tab, TabItem, Swiper, SwiperItem,
      CostApplyForm, UploadImage, Popup, XSwitch, ChoiceApprover, PopupHeader
    },
    data() {
      return {
        currentIndex: 0,//当前报销单tab
        workOrderCode: '',//工单编号
        workOrderList: [],
        sprPopup: false,//审批人弹窗
        approvalList: [],//当前选择人列表
        contentList: [],//报销单form内容
      }
    },
    computed: {
      allFillAmount() {
        this.fillAmount = this.contentList.reduce((total, item) => {
          return parseFloat(total || 0) + parseFloat(item.fillFigure || 0);
        }, 0);
        return this._numberComma(this.fillAmount);
      },
    },
    created() {
      this.addTab();
      let params = {
        include: true,
        fields: 'code', engineerId: this.$store.state.user.userInfo.id, systemStatus: '1,2,3,4,5,6,7', noPage: true
      }
      this.$http.get('/work/api/workorder', {params: params}).then(res => {
          if (res.data.data.length == 0) {
            this.$vux.alert.show({
              title: '提醒',
              content: '暂无可报销的工单！',
              onHide: () => {
                this.$router.go(-1)
              }
            })
          }
          this.workOrderList = res.data.data.map(r => {
            return r.code;
          })
        }
      )
    },
    mounted() {
      this.$getUserInfo();
      if (this.$route.query.id) {
        this.$http.get('/expense/api/RequestForm/' + this.$route.query.id).then(res => {
            // 格式化后端数据至前端
            let object = res.data.data;
            this.id = object.id;
            this.workOrderCode = object.workOrderCode;
            this.fillAmount = object.fillAmount;
            //默认返回的审核人都是已经选中
            object.trials.forEach(item => {
              item.checked = true;
            });
            this.approvalList = object.trials;
            let promisesAll = [];
            object.requestFormItems.forEach(item => {
              promisesAll.push(new Promise((resolveAll, rejectAll) => {
                item.subjectList = JSON.parse(item.subjectContent);
                item.subjectContent = {};
                item.count = item.count || '';
                let promisesItemAll = [];
                if (item.subjectList.length == 0) {
                  resolveAll();
                }
                item.subjectList.forEach(r => {
                  promisesItemAll.push(new Promise((resolveItemAll, rejectItemAll) => {
                    item.subjectContent[r.key] = r.value;
                    if (r.type === 'select') {
                      if (r.key === 'shipLevel') {
                        this.$http.get('/expense/api/shipLevel', {
                          params: {
                            subjectCode: item.subjectCode,
                            noPage: true,
                          }
                        }).then(dic => {
                          if (dic.data.data) {
                            dic.data.data = dic.data.data.map(item => {
                              return item.shipLevel;
                            });
                            r.dict = r.key;//特意处理仓位等级没有dict字段
                            item.subjectSelect = item.subjectSelect || {};
                            item.subjectSelect[r.dict] = dic.data.data;
                            resolveItemAll();
                          }
                          else
                            resolveItemAll()
                        });
                      } else {
                        this.$http.get('/account/api/dict', {
                          params: {
                            codeLike: r.dict,
                            include: true,
                            noPage: true,
                            fields: 'id,code,name'
                          }
                        }).then(dic => {
                          if (dic.data.data) {
                            dic.data.data = dic.data.data.map(item => {
                              return item.name;
                            });
                          }
                          item.subjectSelect = item.subjectSelect || {};
                          item.subjectSelect[r.dict] = dic.data.data;
                          resolveItemAll();
                        });
                      }
                    } else {
                      resolveItemAll();
                    }
                  }));
                });
                Promise.all(promisesItemAll).then(resp => {
                  resolveAll()
                });
              }));
            });
            Promise.all(promisesAll).then(() => {
              this.contentList = object.requestFormItems;
              //确定科目类别之再确定高度
              this.setHeight();
            })
          }
        )
      }
      else {
        this.setHeight();
      }
    },
    watch: {},
    methods: {
      validate() {
        let _is = true;
        for (let ref in this.$refs.swiper_item[0].$refs) {
          this.$refs.swiper_item[0].$refs[ref].setTouched();
          this.$refs.swiper_item[0].$refs[ref].validate();
          if (!this.$refs.swiper_item[0].$refs[ref].valid)
            _is = this.$refs.swiper_item[0].$refs[ref].valid
        }
        return _is;
      },
      //设置swapper高度
      setHeight() {
        this.$nextTick(() => {
          this.$refs.swiper.xheight = this.$refs.swiper_item[0].$el.clientHeight + 'px'
        })
      },
      //弹出拍照界面
      showPopup() {
        this.bxdPopup = !this.bxdPopup
      },
      //弹出申请人面
      addApprovalSure(list) {
        this.sprPopup = !this.sprPopup;
        if (list) {
          list.forEach(item => {
            item.checked = false;
          })
        }
      },
      // 添加申请人
      addApproval(list) {
        //如果请求数据了，就不再请求
        if (list && list.length > 0) {
          this.approvalList = list;
          this.sprPopup = !this.sprPopup;
          return
        }
        let params = {
          departmentId: this.$store.state.user.userInfo.departmentBean.id,
          typeStatus: 5,
        };
        //获取对应的申请人ids
        let getList = new Promise((resolve, reject) => {
          this.$http.get('/expense/api/auditConfiguration', {params: params}).then(res => {
              resolve(res.data.data.rows);
            }
          )
        });
        getList.then(data => {
          let userIds = data.map(function (r) {
            return r.userId
          });
          let param = {
            userIds: userIds.join(','),
            include: true,
            fields: 'nickName,id'
          };
          // 获取申请人的详情
          this.$http.get('/expense/api/auditConfiguration/user', {params: param}).then(res => {
              res.data.data.forEach(item => {
                item.checked = false;
                list.push(item)
              });
              this.approvalList = list;
              this.sprPopup = !this.sprPopup;
            }
          )
        });
      },
      //添加明细
      addTab() {
        //添加表单项，存在则验证，不存在就是添加第一个表单
        if (this.contentList.length > 0) {
          if (this.validate())
            this.addList();
        } else {
          this.addList();
        }
      },
      //添加明细提取方法
      addList() {
        this.contentList.push({
          subject: '',
          subjectCode: '',
          subjectName: '',
          subjectList: [],
          subjectContent: {},
          fillFigure: '',
          count: '',
          state: '',
          subjectSelect: {},
        });
        this.$nextTick(() => {
          this.currentIndex = this.contentList.length - 1;
        });
      },
      //删除明细
      removeTab(index) {
        this.$vux.confirm.show({
          title: '提醒',
          content: '是否确定删除？',
          onCancel: () => {

          },
          onConfirm: () => {
            if (this.contentList.length > 1) {
              this.contentList.splice(index, 1)
              this.currentIndex = index - 1;//当前报销单tab
            }
          }
        })
      },
      // 保存/提交审核  格式化前端数据至后端
      submitExpense(index) {
        if (!this.workOrderCode) {
          this.$vux.toast.show({text: '工单必填', type: 'warn'});
          return
        }
        if (this.approvalList.length <= 0||this.approvalList.filter(r=>{ return r.checked == true}).length<=0) {
          this.$vux.toast.show({text: '审核人必填', type: 'warn'});
          return
        }
        // 界面验证规则
        if (!this.validate()) {
          return
        }
        let txt = '';
        this.contentList.forEach((item, index) => {
          if (!item.subjectCode) {
            if (!txt)
              txt = '明细' + (index + 1) + '科目必填'
            return
          }
          if (!item.count) {
            if (!txt)
              txt = '明细' + (index + 1) + '申请数量必填'
            return
          }
          if (!item.fillFigure) {
            if (!txt)
              txt = '明细' + (index + 1) + '申请金额必填'
            return
          }
          if(item.subjectList.length > 0){
            item.subjectList.forEach(r=>{
               if(r.required&&!item.subjectContent[r.key]){
                 if (!txt)
                   txt = '明细' + (index + 1) +r.label+ '必填'
                 return
               }
            });
          }
        });
        if(txt){
          this.$vux.toast.show({text: txt, type: 'warn'});
          return
        }
        let requestFormItems = this.contentList.map(item => {
          return {
            "fillFigure": item.fillFigure,
            "count": item.count,
            "state": item.state,
            "subjectCode": item.subjectCode,
            "subjectName": item.subjectName,
            "subjectContent": JSON.stringify(item.subjectList.map(r => {
              r.value = item.subjectContent[r.key];
              return r
            })),
          }
        });
        let params = {
          "requestFormItems": requestFormItems,
          "requestUser": {id: this.$store.state.user.userInfo.id},
          "fillAmount": this.fillAmount,
          "trials": this.approvalList.filter(r => {
            return r.checked
          }).map(r => {
            return {
              "id": r.id,
            }
          }),
          "status": index,
          "workOrderCode": this.workOrderCode
        };
        this.$vux.confirm.show({
          title: '提醒',
          content: '请检查数据是否填写完整，提交后无法撤回，是否确定提交？',
          onCancel: () => {

          },
          onConfirm: () => {
            if (this.id) {
              this.$http.put('/expense/api/RequestForm', params).then(res => {
                  this.$vux.toast.show({
                    type: "success",
                    text: '提交成功',
                    onHide: () => {
                      this.$router.back(-1);
                    }
                  })
                }
              )
            } else {
              this.$http.post('/expense/api/RequestForm', params).then(res => {
                  this.$vux.toast.show({
                    type: "success",
                    text: '提交成功',
                    onHide: () => {
                      this.$router.back(-1);
                    }
                  })
                }
              )
            }
          }
        })
      }
      ,
      cancelCommit() {
        this.$vux.confirm.show({
          title: '提醒',
          content: '是否确定放弃操作？',
          onCancel: () => {

          },
          onConfirm: () => {
            this.$router.back(-1);
          }
        })
      },
    },
  }
</script>

<style lang="less">
  .createApplyForm {
    .weui-label {
      text-align-last: justify;
      padding-right: .1rem;
    }
    .vux-label {
      text-align-last: justify;
      padding-right: .1rem;
    }
    .weui-cells{
      line-height: 1.3em;
    }
    .weui-cell {
      line-height: 1.5em;
      padding: 5px 10px;
    }
    .weui-input{
      line-height: 1.5em;
      height: 1.5em;
    }
    .submit {
      .weui-cells {
        line-height: 0.43rem;
        .star {
          width: 30%;
          float: left;
          text-align: center;
        }
        .close {
          width: 50%;
          float: left;
          text-align: center;
          border-right: 1px solid #E5E5E5;
        }
        .checkmark {
          width: 50%;
          float: left;
          background: #43A2FE;
          color: white;
          text-align: center;
          .weui-icon-success-circle {
            color: white;
            font-size: 20px;
          }
        }
      }
    }
    .addPerson {
      .weui-cells {
        padding: 15px;
        span {
          font-size: 13px;
          line-height: 13px;
          color: #8b8b8b;
        }
      }
    }
    .clearfix:after {
      content: "020";
      display: block;
      height: 0;
      clear: both;
      visibility: hidden;
    }
    .vux-tab-item .weui-icon-cancel {
      color: #3FBCFC;
      font-size: 19px;
      margin-top: -2px;
    }
    .add-item {
      float: right;
      font-size: 0.12rem;
      height: 0.24rem;
      line-height: 0.24rem;
      margin-top: 0.2rem;
      padding-left: 0.29rem;
      padding-right: 0.1rem;
      background: url('~assets/images2/icon_tianjiafeiyong@2x.png') no-repeat;
      background-size: auto 100%;
    }
    .weui-cells {
      ol {
        padding: 20px 0;
        li {
          width: 25%;
          float: left;
          margin-bottom: 5px;
          .item_box {
            text-align: center;
            position: relative;
            > i {
              position: absolute;
              top: -10px;
              left: 5px;
              color: #C15E67;
            }
            > img {
              height: 50px;
              width: 50px;
            }
            > div {
              text-align: center;
              font-size: 13px;
              padding: 5px 0;
            }
          }
        }
      }
      .vux-selector.weui-cell_select {
        padding: 5px 10px;
        .weui-select {
          height: 1.5em;
          line-height: 1.5em;
        }
      }
      .weui-cell_select .weui-cell__bd:after {
        border-color: #3FBCFC;
        right: 22px;
      }
    }

    .vux-x-input, .weui-cell_select, .vux-x-textarea {
      .weui-cell__bd {
        padding: 2px;
        border: 0.01rem solid #E5E5E5;
        border-radius: 5px;
      }
    }
    .vux-flexbox {
      .vux-flexbox-item {
        border-radius: 0;
        .weui-btn_primary {
          background: #43A2FE;
          color: #fff;
          .weui_icon_success-circle {
            color: #fff;
          }
        }
        .weui-btn_warn {
          color: #333333;
          background: #fff;
        }
        .weui-btn {
          border-radius: 0;
          &:after {
            border-radius: 0;
          }
        }
      }
    }
    .weui-cell__ft {

      .vux-x-input-right-full {
        margin-left: 0px;
        img {
          height: 12px;
          margin-top: 15px;
          margin-left: -12px;
          margin-right: 5px;
        }
      }
    }
  }
</style>
